package com.dream.base.web.interceptor;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.dream.utils.annotation.AccessToken;
import com.dream.utils.annotation.AccessTokenType;
import com.dream.vo.base.Constants;


/**
 * @copyright evan
 * @author evan
 * @Revision
 * @date 2013/09/1
 */
public class AccessTokenInterceptor extends HandlerInterceptorAdapter {

	
	@Override
	public boolean preHandle(HttpServletRequest httpRequest, HttpServletResponse response, Object handler)
			throws ServletException, IOException {

		boolean proceed = true;

		if (handler instanceof HandlerMethod) {

			Method method = (Method) ((HandlerMethod) handler).getMethod();
			if (method.isAnnotationPresent(AccessToken.class)) {

				AccessToken token = method.getAnnotation(AccessToken.class);
				AccessTokenType value = token.value();
				
				if (AccessTokenType.generate == value) {//generate a key
					setTokenValue(httpRequest);
				}else{//verify token
					
					proceed = verifyTokenValue(httpRequest);
					
				}
			}

		}
		return proceed;
	}
	
	private boolean verifyTokenValue(HttpServletRequest httpRequest){
		
		boolean isOk = false;
		HttpSession session = httpRequest.getSession(false);
		String token = (String)session.getAttribute(Constants.TOKEN_NAME);
		String pageVal = httpRequest.getParameter(Constants.TOKEN_NAME);
		if(StringUtils.isNotBlank(token) && token.equals(pageVal)){//verify is ok and change session value
			isOk = true;
			setTokenValue(httpRequest);
			
		}
		return isOk;
	}
	
	private void setTokenValue(HttpServletRequest httpRequest){
		
		HttpSession session = httpRequest.getSession(false);
		String token = UUID.randomUUID().toString();
		session.setAttribute(Constants.TOKEN_NAME,token);
		
	}
	
}
